<?php

namespace App\Services;

use App\Exceptions\GeneralException;
use App\Models\Admin;
use Earnp\GoogleAuthenticator\Facades\GoogleAuthenticator;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class AdminService
{
    public function privilegeService(): PrivilegeService
    {
        return getDependentObject($this, PrivilegeService::class, 'privilegeService');
    }

    /**
     * 获取用户信息和用户可用菜单
     * @param Admin $admin
     * @return array
     */
    public function getAdminInfo(Admin $admin)
    {
        return [
            'menus' => $this->privilegeService()->getMenusByAdmin($admin),
            'name' => $admin->username,
        ];
    }

    /**
     * 后台用户列表
     *
     * @param $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getIndex($params)
    {
        $page = !empty($params['page']) ? $params['page'] : 1;
        $limit = !empty($params['limit']) ? $params['limit'] : 10;
        $status = isset($params['status']) ? $params['status'] : null;
        $account = !empty($params['account']) ? $params['account'] : null;
        $username = !empty($params['username']) ? $params['username'] : null;
        $query = Admin::query();
        if ($status === '0' || $status) {
            $query->where('status', $status);
        }
        if ($username) {
            $query->where('username', 'like', "%{$username}%");
        }
        if ($account) {
            $query->where('account', 'like', "%{$account}%");
        }
        return $query->where('id', '>', 1)->orderByDesc('created_at')->paginate($limit, ['*'], 'page', $page);
    }

    /**
     * 后台用户信息
     *
     * @param int $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     */
    public function showAdmin(int $id)
    {
        $admin = Admin::query()->with('roles')->findOrFail($id);
        return $admin;
    }

    /**
     * 添加后台用户
     * @param $params
     * @return Admin
     * @throws GeneralException
     */
    public function storeAdmin($params)
    {
        $admin = new Admin();
        DB::beginTransaction();
        try {
            $admin->fill($params);
            $admin->save();
            if (!empty($params['roles'])) {
                $admin->roles()->sync($params['roles']);
            } else {
                $admin->roles()->detach();
            }
            Artisan::call('privileges:clear');
            DB::commit();
        } catch (\Exception $e) {
            Log::error('新增后台用户失败：' . $e->getMessage());
            DB::rollBack();
            throw new GeneralException('服务器错误');
        }
        return $admin;
    }

    /**
     * 修改后台用户
     * @param $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     * @throws GeneralException
     */
    public function updateAdmin($params)
    {
        $admin = Admin::query()->findOrFail($params['id']);
        if (isset($params['account'])) unset($params['account']);
        if (isset($params['username'])) unset($params['username']);
        DB::beginTransaction();
        try {
            $admin->fill($params);
            $admin->save();
            if (!empty($params['roles'])) {
                $admin->roles()->sync($params['roles']);
            } else {
                $admin->roles()->detach();
            }
            Artisan::call('privileges:clear');
            DB::commit();
        } catch (\Exception $e) {
            Log::error('修改后台用户失败：' . $e->getMessage());
            DB::rollBack();
            throw new GeneralException('服务器错误');
        }
        return $admin;
    }

    /**
     * Description:刷新谷歌验证码
     * @param Admin $admin
     * @param $code
     * @return mixed
     * @throws GeneralException
     */
    public function refreshGoogleSecret(Admin $admin, $code)
    {
        $oldSecret = $admin->google_secret;
        if (empty($oldSecret)) {
            $newSecret = GoogleAuthenticator::CreateSecret()['secret'];
            $admin->google_secret = $newSecret;
            $admin->save();
            return $newSecret;
        }else{
            $check = GoogleAuthenticator::CheckCode($oldSecret,$code);
            if($check){
                $newSecret = GoogleAuthenticator::CreateSecret()['secret'];
                $admin->google_secret = $newSecret;
                $admin->save();
                return $newSecret;
            }else{
                throw new GeneralException('google 验证码错误');
            }
        }
    }

    /**
     * Description:修改登录密码
     * @param Admin $admin
     * @param array $params
     * @return bool
     * @throws GeneralException
     */
    public function updatePassword(Admin $admin,array $params)
    {
        $check = Hash::check($params['old_password'], $admin->password);
        if(!$check){
            throw new GeneralException('旧密码不正确');
        }
        $admin->password = $params['password'];
        $admin->save();
        return true;
    }
}
